package com.topscore.uke.network.retrofit;

import com.google.gson.JsonParseException;
import com.topscore.uke.mvp.model.BaseHttpListener;
import com.topscore.utillibrary.util.L;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.ParseException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * Created by 71468 on 2017/9/13.
 */

public abstract class HandleErrorSubscriber<T> extends Subscriber<T> {

    private BaseHttpListener mHttpListener;

    public HandleErrorSubscriber(BaseHttpListener httpListener) {
        this.mHttpListener = httpListener;
    }

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        mHttpListener.onComplete();
        if (e instanceof SocketTimeoutException
                || e instanceof ConnectException
                || e instanceof HttpException){
            mHttpListener.onError(-2,"网络不给力");
        }else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException){
            mHttpListener.onError(-1,"数据解析错误");
        }else if (e instanceof ResultException){
            ResultException exception = (ResultException) e;
            mHttpListener.onError(exception.getCode(),exception.getMessage());
            L.e(exception.toString());
        }
        else {
            L.e(e.toString());
            mHttpListener.onError(-1,"未知错误");
        }
    }

    @Override
    public void onNext(T response) {
        mHttpListener.onComplete();
        onSuccess(response);
    }

    public abstract void onSuccess(T response);
}
